/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
 */
package td.server.handler;

import td.domain.Thought;
import td.domain.util.LoadGroup;
import td.server.dao.ThoughtDao;
import td.shared.Constants.MSG;
import td.shared.action.AbstractThoughtAction;
import td.shared.action.result.AbstractResult;
import td.shared.action.result.AbstractResult.Status;

import com.google.inject.Inject;

/**
 * Base class for handlers that operate on a thought.
 * 
 * @author Artem Shamsutdinov
 * 
 */
public abstract class AbstractThoughtHandler<A extends AbstractThoughtAction<R>, R extends AbstractResult>
		extends AbstractHandler<A, R> {

	@Inject
	ThoughtDao thoughtDao;

	boolean isThoughtOwner;
	private Thought thought = null;
	private Class<? extends LoadGroup>[] thoughtLoadGroups = null;

	protected AbstractThoughtHandler(boolean isProtected, boolean isThoughtOwner) {
		super(isProtected);
		this.isThoughtOwner = isThoughtOwner;
	}

	protected final void setThoughtLoadGroups(
			Class<? extends LoadGroup>... thoughtLoadGroups) {
		this.thoughtLoadGroups = thoughtLoadGroups;
	}

	protected final Class<? extends LoadGroup>[] getThoughtLoadGroups() {
		return thoughtLoadGroups;
	}

	@Override
	protected void validate(A action) throws ValidationException {
		super.validate(action);
		thought = thoughtDao.get(action.getThoughtId(), thoughtLoadGroups);
		if (thought == null) {
			throw new ValidationException(Status.DATA_ERROR, MSG.THOUGHT_NOT_FOUND);
		}
		if (isThoughtOwner) {
			if (getThinker() == null) {
				throw new ValidationException(Status.DATA_ERROR, MSG.THINKER_NOT_FOUND);
			} else if (!getThinker().getId().equals(thought.getThinkerId())) {
				throw new ValidationException(Status.ACCESS_ERROR,
						MSG.THINKER_NOT_OWNER_OF_THOUGHT);
			}
		}
	}

	protected Thought getThought() {
		return thought;
	}

	void setThought(Thought thought) {
		this.thought = thought;
	}
}
